<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="45%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="160px">
        <el-form-item prop="image">
          <template #label><span class="required">*</span> 商品主图</template>
          <ImageUpload v-model="formData.image" :limit="1" />
        </el-form-item>
        <el-form-item prop="images">
          <template #label><span class="required">*</span> 商品轮播图</template>
          <ImageUpload v-model="formData.images" :limit="5" multiple />
        </el-form-item>
        <el-form-item prop="title">
          <template #label><span class="required">*</span> 商品名称</template>
          <el-input v-model="formData.title" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品简介" prop="info">
          <el-input v-model="formData.info" placeholder="请输入商品简介" type="textarea" />
        </el-form-item>
        <el-form-item prop="unitName">
          <template #label><span class="required">*</span> 单位</template>
          <el-input v-model="formData.unitName" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item prop="startTime">
          <template #label><span class="required">*</span> 活动时间</template>
          <el-date-picker
            v-model="activityTimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="timestamp"
            format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item prop="peopleNum">
          <template #label><span class="required">*</span> 砍价人数</template>
          <el-input v-model="formData.peopleNum" placeholder="需邀请多少人砍价成功" />
        </el-form-item>
        <el-form-item prop="bargainNum">
          <template #label><span class="required">*</span> 帮砍人数</template>
          <el-input v-model="formData.bargainNum" placeholder="单个商品用户可以帮砍的次数" />
        </el-form-item>
        <el-form-item prop="num">
          <template #label><span class="required">*</span> 单次砍价次数</template>
          <el-input v-model="formData.num" placeholder="单个活动每个用户发起砍价次数限制" />
        </el-form-item>
        <el-form-item prop="bargainMaxPrice">
          <template #label><span class="required">*</span> 单次砍价金额</template>
          <el-input v-model="formData.bargainMaxPrice" placeholder="请输入单次砍价金额" />
        </el-form-item>
        <el-form-item prop="quota">
          <template #label><span class="required">*</span> 购买数量限制</template>
          <el-input v-model="formData.quota" placeholder="请输入购买数量限制" />
        </el-form-item>
        <el-form-item prop="tempId">
          <template #label><span class="required">*</span> 运费模板</template>
          <el-select v-model="formData.tempId" placeholder="请选择运费模板">
            <el-option
              v-for="item in shippingTemplates"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="status">
          <template #label><span class="required">*</span> 砍价状态</template>
          <el-radio-group v-model="formData.status">
            <el-radio :label="0">关闭</el-radio>
            <el-radio :label="1">开启</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 商品属性表格 -->
        <el-form-item label="商品规格:">
          <el-radio-group v-model="productForm.specType">
            <el-radio :label="0">单规格</el-radio>
            <el-radio :label="1">多规格</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <!-- 多规格操作区域 -->
            <div v-if="productForm.specType === 1" class="spec-operation">
              <el-form-item label="商品规格:">
                <el-select v-model="selectedSpec" placeholder="请选择" size="small" style="width: 180px">
                  <el-option v-for="item in cascaderAttrData" :key="item.id" :label="item.ruleName" :value="item.id"></el-option>
                </el-select>
                <el-button type="primary" size="small" @click="confirmSpec">确认</el-button>
                <el-button size="small" @click="openAddSpecDialog">添加规格</el-button>
              </el-form-item>

              <!-- 已选规格列表 -->
              <div class="spec-list w-full">
                <div v-for="(specGroup, groupIndex) in selectedSpecGroups" :key="groupIndex" class="spec-item">
                  <h3 class="spec-name">{{ specGroup.spec }}：</h3>
                  <el-tag v-for="(value, valueIndex) in specGroup.values" :key="valueIndex" size="small" closable @close="removeSpecValue(groupIndex, valueIndex)" class="spec-tag">
                    {{ value }}
                  </el-tag>
                  <el-button type="text" size="small" class="add-btn" @click="openAddSpecValueDialog(groupIndex)">
                    <i class="fa fa-plus-circle"></i> 添加
                  </el-button>
                  <el-button type="text" size="small" class="delete-btn" @click="removeSpecGroup(groupIndex)">
                    <i class="fa fa-trash"></i> 删除
                  </el-button>
                </div>
              </div>

              <!-- 批量设置 -->
              <div v-if="productForm.specType === 1 && showSpecTable" style="margin-bottom: 16px;">
                <el-form-item label="批量设置：" style="margin-bottom: 16px;">
                  <el-table :data="[batchForm]" border>
                    <el-table-column prop="tableImage" label="图片" align="center" width="95px">
                      <template>
                        <ImageUpload v-model="batchForm.tableImage" :isShowTip="false" :limit="1" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="price" label="售价" align="center">
                      <template>
                        <el-input-number v-model="batchForm.price" :min="0" :step="1" :precision="2" style="width: 120px;" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="cost" label="成本价" align="center">
                      <template>
                        <el-input-number v-model="batchForm.cost" :min="0" :step="1" :precision="2" style="width: 120px;" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="otPrice" label="原价" align="center">
                      <template>
                        <el-input-number v-model="batchForm.otPrice" :min="0" :step="1" :precision="2" style="width: 120px;" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="stock" label="库存" align="center">
                      <template>
                        <el-input-number v-model="batchForm.stock" :min="0" :step="1" :precision="0" style="width: 120px;" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="weight" label="重量（KG）" align="center">
                      <template>
                        <el-input-number v-model="batchForm.weight" :min="0" :step="1" :precision="2" style="width: 120px;" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="volume" label="体积(m³)" align="center">
                      <template>
                        <el-input-number v-model="batchForm.volume" :min="0" :step="1" :precision="2" style="width: 120px;" />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="100">
                      <template>
                        <el-button type="text" @click="handleBatchSet" style="color: #409EFF;">批量添加</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form-item>
              </div>
            </div>

            <!-- 添加规格弹窗 -->
            <el-dialog title="添加规格" :visible.sync="addSpecDialogVisible" width="30%" :before-close="handleAddSpecClose">
              <el-form :model="addSpecForm" label-width="80px">
                <el-form-item label="规格">
                  <el-input v-model="addSpecForm.spec" placeholder="请输入规格名称"></el-input>
                </el-form-item>
                <el-form-item label="规格值">
                  <el-input v-model="addSpecForm.value" placeholder="请输入规格值"></el-input>
                </el-form-item>
              </el-form>
              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="addSpecDialogVisible = false">取消</el-button>
                  <el-button type="primary" @click="confirmAddSpec">确认</el-button>
                </span>
              </template>
            </el-dialog>

            <!-- 添加规格值弹窗 -->
            <el-dialog title="添加规格值" :visible.sync="addSpecValueDialogVisible" width="30%" :before-close="handleAddSpecValueClose">
              <el-form :model="addSpecValueForm" label-width="80px">
                <el-form-item label="规格值">
                  <el-input v-model="addSpecValueForm.value" placeholder="请输入规格值"></el-input>
                </el-form-item>
              </el-form>
              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="addSpecValueDialogVisible = false">取消</el-button>
                  <el-button type="primary" @click="confirmAddSpecValue">确认</el-button>
                </span>
              </template>
            </el-dialog>

            <!-- 删除规格确认弹窗 -->
            <el-dialog title="确认删除" :visible.sync="deleteDialogVisible" width="30%" :before-close="handleDeleteClose">
              <div slot="content">
                确定要删除规格"{{ deletingSpec }}"吗？
              </div>
              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="deleteDialogVisible = false">取消</el-button>
                  <el-button type="danger" @click="confirmDeleteSpec">确认删除</el-button>
                </span>
              </template>
            </el-dialog>

            <!-- 表格区域 -->
            <div class="mt-6 center-table">
              <!-- 单规格 -->
              <el-table v-if="productForm.specType === 0" :data="tableData" border>
                <el-table-column prop="tableImage" label="图片" width="100px">
                  <template slot-scope="scope">
                    <ImageUpload v-model="scope.row.tableImage" :isShowTip="false" :limit="1" />
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="售价">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.price" :min="0" :step="1" :precision="2" placeholder="0" style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="cost" label="成本价">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.cost" :min="0" :step="1" :precision="2" placeholder="0" style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="otPrice" label="原价">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.otPrice" :min="0" :step="1" :precision="2" placeholder="0" style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="stock" label="库存">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.stock" :min="0" :step="1" :precision="0" placeholder="0" style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="weight" label="重量（KG）">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.weight" :min="0" :step="1" :precision="2" placeholder="0" style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="volume" label="体积(m³)">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.volume" :min="0" :step="1" :precision="2" placeholder="0" style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="productNo" label="商品编号" v-if="false">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.productNo" placeholder=""></el-input>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 多规格 -->
              <el-table :data="multipleSpecTableData" border size="small" style="width: 100%" v-if="productForm.specType === 1 && showSpecTable">
                <!-- 动态生成规格列 -->
                <el-table-column v-for="specGroup in selectedSpecGroups" :key="specGroup.spec.toString()" :prop="specGroup.spec.toString()" :label="specGroup.spec.toString()" width="100px"></el-table-column>
                <el-table-column prop="tableImage" label="图片" width="92px">
                  <template slot-scope="scope">
                    <ImageUpload v-model="scope.row.tableImage" :isShowTip="false" :limit="1" />
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="售价">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.price" :min="0" :step="1" :precision="2" placeholder="0" style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="cost" label="成本价">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.cost" :min="0" :step="1" :precision="2" placeholder="0" style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="otPrice" label="原价">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.otPrice" :min="0" :step="1" :precision="2" placeholder="0" style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="stock" label="库存">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.stock" :min="0" :step="1" :precision="0" placeholder="0" style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="weight" label="重量（KG）">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.weight" :min="0" :step="1" :precision="2" placeholder="0" style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="volume" label="体积(m³)">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.volume" :min="0" :step="1" :precision="2" placeholder="0" style="width: 100%;" @keydown.native="numberKeydown($event)"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="productNo" label="商品编号" v-if="false">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.productNo" placeholder=""></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>
        <!-- 隐藏域 productId 和 deleted 不显示在表单中 -->
        <input type="hidden" v-model="formData.productId" />
        <input type="hidden" v-model="formData.deleted" />
        <div style="text-align:right;margin-top:20px;">
          <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import * as BargainApi from '@/api/store/bargain';
import ImageUpload from '@/components/ImageUpload';
import { getProductSpecList } from '@/api/store/product';
export default {
  name: "BargainForm",
  components: { ImageUpload },
  data() {
    return {
      dialogTitle: "",
      dialogVisible: false,
      formLoading: false,
      formData: {
        productId: undefined,
        image: undefined,
        images: undefined,
        title: undefined,
        info: undefined,
        unitName: undefined,
        startTime: null,
        stopTime: null,
        peopleNum: undefined,
        bargainNum: undefined,
        num: undefined,
        bargainMaxPrice: undefined,
        quota: undefined,
        tempId: undefined,
        status: 1,
        deleted: 0,
      },
      activityTimeRange: [],
      formRules: {
        image: [{ required: true, message: '商品主图不能为空', trigger: 'blur' }],
        images: [{ required: true, message: '商品轮播图不能为空', trigger: 'blur' }],
        title: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
        unitName: [{ required: true, message: '单位不能为空', trigger: 'blur' }],
        startTime: [{ required: true, message: '活动开始时间不能为空', trigger: 'change' }],
        stopTime: [{ required: true, message: '活动结束时间不能为空', trigger: 'change' }],
        peopleNum: [{ required: true, message: '砍价人数不能为空', trigger: 'blur' }],
        bargainNum: [{ required: true, message: '帮砍人数不能为空', trigger: 'blur' }],
        num: [{ required: true, message: '单次砍价次数不能为空', trigger: 'blur' }],
        bargainMaxPrice: [{ required: true, message: '单次砍价金额不能为空', trigger: 'blur' }],
        quota: [{ required: true, message: '购买数量限制不能为空', trigger: 'blur' }],
        tempId: [{ required: true, message: '运费模板不能为空', trigger: 'change' }],
        status: [{ required: true, message: '砍价状态不能为空', trigger: 'change' }],
      },
      specList: [
        {
          image: '',
          bargainStartPrice: 0,
          bargainMinPrice: 0,
          cost: 0,
          price: 0,
          stock: 0,
          quota: 0,
          weight: 0,
          volume: 0,
          productCode: ''
        }
      ],
      shippingTemplates: [
        { id: 1, name: '全国包邮' },
        { id: 2, name: '港澳台不包' },
        // 你需要的其他模板
      ],
      productForm: {
        specType: 0,
      },
      selectedSpec: '',
      selectedSpecGroups: [],
      batchForm: {
        tableImage: '',
        price: 0,
        cost: 0,
        otPrice: 0,
        stock: 0,
        weight: 0,
        volume: 0,
      },
      addSpecDialogVisible: false,
      addSpecForm: {
        spec: '',
        value: '',
      },
      addSpecValueDialogVisible: false,
      addSpecValueForm: {
        value: '',
      },
      deleteDialogVisible: false,
      deletingSpec: '',
      deletingIndex: -1,
      currentGroupIndex: -1,
      tableData: [],
      multipleSpecTableData: [],
      showSpecTable: false,
      cascaderAttrData: [],
    };
  },
  watch: {
    activityTimeRange(val) {
      if (val && val.length === 2) {
        this.formData.startTime = Number(val[0]);
        this.formData.stopTime = Number(val[1]);
      } else {
        this.formData.startTime = null;
        this.formData.stopTime = null;
      }
    },
    'formData.startTime': {
      handler(val) {
        if (val && this.formData.stopTime) {
          this.activityTimeRange = [Number(this.formData.startTime), Number(this.formData.stopTime)];
        }
      },
      immediate: true
    },
    'formData.stopTime': {
      handler(val) {
        if (val && this.formData.startTime) {
          this.activityTimeRange = [Number(this.formData.startTime), Number(this.formData.stopTime)];
        }
      },
      immediate: true
    }
  },
  methods: {
    async open(id) {
      this.dialogVisible = true;
      this.reset();

      if (id) {
        this.formLoading = true;
        try {
          const res = await BargainApi.getBargain(id);
          this.formData = res.data;

          // 处理images字段：解析JSON字符串或逗号分隔的字符串为数组
          if (this.formData.images) {
            try {
              // 尝试解析 JSON 字符串
              const parsedImages = JSON.parse(this.formData.images);
              this.formData.images = Array.isArray(parsedImages) ? parsedImages : [parsedImages];
            } catch (e) {
              // 如果不是 JSON 格式，按逗号分隔
              this.formData.images = this.formData.images.split(',').filter(img => img.trim());
            }
          } else {
            this.formData.images = [];
          }

          this.formData.startTime = Number(res.data.startTime);
          this.formData.stopTime = Number(res.data.stopTime);
          this.activityTimeRange = [Number(res.data.startTime), Number(res.data.stopTime)];
          this.title = "修改砍价";
          // 自动根据id查询商品属性
          if (res.data.id) {
            const productRes = await getProductSpecList(res.data.id);
            this.specList = productRes.data || [];
          }
        } finally {
          this.formLoading = false;
        }
      } else {
        this.title = "新增砍价";
      }
    },
    async submitForm() {
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = { ...this.formData }; // 创建副本避免修改原数据

        // 处理images字段：将数组转换为逗号分隔的字符串
        if (data.images && Array.isArray(data.images)) {
          data.images = data.images.join(',');
          console.log('提交时的images(数组转字符串):', data.images);
        } else if (data.images && typeof data.images === 'string') {
          // 如果已经是字符串格式，直接使用
          console.log('提交时的images(已经是字符串):', data.images);
          data.images = data.images;
        } else {
          console.log('提交时的images(设置为空字符串)');
          data.images = '';
        }

        if (this.activityTimeRange && this.activityTimeRange.length === 2) {
          data.startTime = Number(this.activityTimeRange[0]);
          data.stopTime = Number(this.activityTimeRange[1]);
        }
        data.specList = this.specList;
        if (data.id) {
          await BargainApi.updateBargain(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        await BargainApi.createBargain(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    reset() {
      this.formData = {
        productId: undefined,
        image: undefined,
        images: [],
        title: undefined,
        info: undefined,
        unitName: undefined,
        startTime: null,
        stopTime: null,
        peopleNum: undefined,
        bargainNum: undefined,
        num: undefined,
        bargainMaxPrice: undefined,
        quota: undefined,
        tempId: undefined,
        status: 1,
        deleted: 0,
      };
      this.activityTimeRange = [];
      this.specList = [
        {
          image: '',
          bargainStartPrice: 0,
          bargainMinPrice: 0,
          cost: 0,
          price: 0,
          stock: 0,
          quota: 0,
          weight: 0,
          volume: 0,
          productCode: ''
        }
      ];
      this.resetForm("formRef");
    },

    // 添加规格相关方法
    handleAddSpecClose(done) {
      this.addSpecDialogVisible = false;
      done();
    },

    handleAddSpecValueClose(done) {
      this.addSpecValueDialogVisible = false;
      done();
    },

    handleDeleteClose(done) {
      this.deleteDialogVisible = false;
      done();
    },

    // 规格操作方法
    confirmSpec() {
      // 确认规格选择
      console.log('确认规格选择');
    },

    openAddSpecDialog() {
      this.addSpecDialogVisible = true;
      this.addSpecForm = {
        spec: '',
        value: ''
      };
    },

    confirmAddSpec() {
      // 确认添加规格
      console.log('确认添加规格', this.addSpecForm);
      this.addSpecDialogVisible = false;
    },

    openAddSpecValueDialog(groupIndex) {
      this.currentGroupIndex = groupIndex;
      this.addSpecValueDialogVisible = true;
      this.addSpecValueForm = {
        value: ''
      };
    },

    confirmAddSpecValue() {
      // 确认添加规格值
      console.log('确认添加规格值', this.addSpecValueForm);
      this.addSpecValueDialogVisible = false;
    },

    removeSpecValue(groupIndex, valueIndex) {
      // 删除规格值
      console.log('删除规格值', groupIndex, valueIndex);
    },

    removeSpecGroup(groupIndex) {
      // 删除规格组
      this.deletingIndex = groupIndex;
      this.deletingSpec = this.selectedSpecGroups[groupIndex]?.spec || '';
      this.deleteDialogVisible = true;
    },

    confirmDeleteSpec() {
      // 确认删除规格
      console.log('确认删除规格', this.deletingSpec);
      this.deleteDialogVisible = false;
    },

    handleBatchSet() {
      // 批量设置
      console.log('批量设置', this.batchForm);
    }
  }
};
</script>

<style scoped>
.required {
  color: #f56c6c;
  margin-right: 2px;
}
</style>
